package org.cainiao.io.nio.channel.socket;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;
import java.nio.channels.*;

/**
 * <br />
 * <p>
 * Author: Cai Niao(wdhlzd@163.com)<br />
 */
public class SocketTest {

    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = null;
        ServerSocketChannel serverSocketChannel = null;
        NetworkChannel networkChannel = null;
        SelectableChannel selectableChannel = null;
        try (SocketChannel sc = SocketChannel.open()) {
            // 将一个客户端 SocketChannel 连接到远程服务器的地址
            sc.connect(new InetSocketAddress("www.test.com", 8088));
            // 将套接字绑定到指定的本地地址端口，如果没有显式调用 bind() 方法，则在第一次调用 connect() 时系统会自动选择一个本地地址和端口
            sc.bind(new InetSocketAddress("127.0.0.1", 8088));
        }

        try (ServerSocketChannel ssc = ServerSocketChannel.open()) {
            // 主要是为了获得旧的 SocketServer API
            ssc.socket().bind(new InetSocketAddress(8089));
            // 更推荐使用 ServerSocketChannel.bind()
            ssc.bind(new InetSocketAddress(8089));
        }

        try (DatagramChannel dc = DatagramChannel.open()) {
            // TODO
        }

        try (RandomAccessFile raf = new RandomAccessFile("test.txt", "r")) {
            FileChannel fc = raf.getChannel();
        }
    }

}
